'use strict';

exports.index = async ctx => {
  const { query } = ctx.request;
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const loginService = ctx.app.weapp.LoginService.create(ctx.request, ctx.response);
  const checkedData = await loginService.check();
  const { openId } = checkedData.userInfo;
  console.log('participated openId', openId);
  const { userId } = await ctx.model.WechatAccount.findById(openId);// 找到当前用户的id
  const { role, nickNameLike, inviter } = query;
  if (inviter === 'invitees') where.inviterId = userId;
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    order: [
      [ 'id', 'DESC' ],
    ],
    include: [
      {
        model: ctx.model.WechatAccount,
      },
    ],
    where,
  };
  if (role) where.role = role;
  if (nickNameLike) where.nickname = { [ctx.model.Op.like]: `%${nickNameLike}%` };
  const {
    count: total, rows: list,
  } = await ctx.model.User.findAndCountAll(options);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.create = async ctx => {
  const { role } = ctx.state.user;
  if (role === 'admin') {
    ctx.validate({
      phone: { type: 'string' },
      role: { type: 'string' },
    });
    const { phone } = ctx.request.body;
    ctx.body = await ctx.model.User.create({ phone, role });
  } else {
    ctx.status = 403;
  }
};
